package org.jpropelleralt.jview.general.impl;

import java.awt.Image;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import org.jpropelleralt.jview.general.GeneralRenderer;
import org.jpropelleralt.node.Described;
import org.jpropelleralt.node.Illustrated;
import org.jpropelleralt.node.Named;

/**
 * Default implementation of {@link GeneralRenderer},
 * Uses {@link Named}, {@link Described}, {@link Illustrated},
 * {@link Image}, {@link Icon} and {@link Object#toString()}
 */
public class GeneralRendererDefault implements GeneralRenderer {

	/**
	 * Formats {@link GeneralRendererDefault} can render to
	 */
	public enum RenderFormat {
		/**
		 * Display icon, name and description on a single line
		 */
		SINGLE_LINE,
		
		/**
		 * Display icon to left, name and description on two lines to the right
		 */
		TWO_LINE
	}

	private final RenderFormat format;
	
	/**
	 * Create a {@link GeneralRendererDefault}
	 * @param format		The {@link RenderFormat} to use
	 */
	public GeneralRendererDefault(RenderFormat format) {
		this.format = format;
	}
	
	@Override
	public boolean canRender(Object o) {
		//Try to render anything
		return true;
	}

	@Override
	public String getHTML(Object o) {
		if (o == null) {
			return "";
		}
		
		String name = null;
		if (o instanceof Named) {
			Named named = (Named) o;
			name = named.name().get();
		} else {
			name = o.toString();
		}
		
		String description = null;
		if (o instanceof Described) {
			Described described = (Described) o;
			description = described.description().get();
		}

		if (description != null) {
			if (format == RenderFormat.SINGLE_LINE) {
				return "<nobr><b>" + name + "</b> <i>" + description + "</i></nobr>";
			} else {
				return "<b>" + name + "</b><br/><i>" + description + "</i>";
			}
		} else {
			return "<nobr>" + name + "</nobr>";
		}
	}

	@Override
	public Icon getIcon(Object o) {
		
		if (o == null) {
			return null;
		}

		if (o instanceof Icon) {
			Icon icon = (Icon) o;
			return icon;
		}
		if (o instanceof Illustrated) {
			Illustrated illustrated = (Illustrated) o;
			return illustrated.illustration().get();
		}
		if (o instanceof Image) {
			Image image = (Image) o;
			return new ImageIcon(image);
		}
		return null;
	}

}
